/// <reference path="../typings/pixi.js/pixi.js.d.ts" />
import BackgroundGaussianBlur from "../class/BackgroundGaussianBlur";
import SVGGraphics from "../class/SVGGraphics";
import TWEEN, {Tween} from "../class/Tween";
import When from "../class/When";
import {
    VIEW_WIDTH,
    VIEW_HEIGHT,
    VIEW_CENTER,
    L_ANI_TIME,
    B_ANI_TIME,
    M_ANI_TIME,
    S_ANI_TIME,
    on,
    square,
    stageManager,
    renderer
} from "./common";


const ani_ticker = new PIXI.ticker.Ticker();
const ani_tween = new TWEEN();
const jump_tween = new TWEEN();
const FPS_ticker = new PIXI.ticker.Ticker();

export const current_stage = new PIXI.Container();
//加载图片资源
export const loader = new PIXI.loaders.Loader();
loader.add("bg", "./images/1.jpg");
loader.load();

const loading_text = new PIXI.Text("加载中……", { font: "25px 微软雅黑", fill: "#FFF" });
current_stage.addChild(loading_text);

loader.once("complete", renderInit);

function renderInit(loader: PIXI.loaders.Loader, resource: PIXI.loaders.ResourceDictionary) {
    current_stage.removeChild(loading_text);

    // 背景图
    var bg_img = new PIXI.Sprite(resource["bg"].texture);
    bg_img.width = VIEW_WIDTH;
    bg_img.height = VIEW_HEIGHT;

    current_stage.addChild(bg_img);
    /*
     * 中间圆圈部分
     */
    var cen = new PIXI.Container();
    current_stage.addChild(cen);
    var cen_point = new PIXI.Point();
    cen_point.x = VIEW_CENTER.x;
    if (VIEW_HEIGHT >= VIEW_WIDTH * 1.618) {// 如果是超过黄金比例的竖屏，那么将圆圈设定在黄金分割点上，否则设定在中心上
        cen_point.y = VIEW_CENTER.y * 0.618;
    } else {
        cen_point.y = VIEW_CENTER.y;
    }
    cen.pivot = cen_point.clone();
    cen.position = cen_point;

    // 进度圈
    var _min_r = (Math.min(VIEW_WIDTH, VIEW_HEIGHT) / 2);
    var _loader_width = _min_r - Math.min(100, _min_r * 0.1);
    var svgGrap = SVGGraphics.importFromSVG(`<circle cx="0" cy="0" r="${_loader_width}" stroke="#FFF"  stroke-width="1.8" fill="rgba(0,0,0, 0.10)" />`);
    var _grap = svgGrap._graphics;
    _grap.boundsPadding = 2;
    var grap = BackgroundGaussianBlur.ContainerToSprite(_grap, renderer);
    grap.interactive = true;
    grap.anchor = new PIXI.Point(0.5, 0.5);
    // grap.buttonMode = true;
    grap.position = cen_point.clone();
    cen.addChild(grap);

    var grap_blur = new BackgroundGaussianBlur(grap, 15, 10);
    // grap_blur.blur = 50;
    var bg_filters = bg_img.filters || [];
    if (bg_filters.length) {
        bg_filters.push(grap_blur)
    } else {
        bg_filters = [grap_blur]
    }
    bg_img.filters = bg_filters;


    // PS:文字在圆圈中的大小公式为：X^2 + (Len / 2) * X^2 = R^2
    // 文字部分
    // 标题
    var _title_text = "蛇蛇战局";
    var title = new PIXI.Text(_title_text, { font: `${Math.sqrt(4 * square(_loader_width * 0.9) / (4 + square(_title_text.length)))}px 微软雅黑`, align: "center", fill: "#FFF" });
    title.position.x = cen_point.x - title.width / 2;
    title.position.y = cen_point.y - title.height;
    cen.addChild(title);
    // 日期时间
    var _time_text = "Snake Rank Fight"
    var time = new PIXI.Text(_time_text, { font: `${_loader_width / _time_text.length}px 微软雅黑`, align: "center", fill: "#FFF" });
    time.position.x = cen_point.x - time.width / 2;
    time.position.y = cen_point.y;
    cen.addChild(time);
    // 作者
    var _user_text = "By @Gaubee"
    var user = new PIXI.Text(_user_text, { font: `${Math.sqrt(4 * square(_loader_width * 0.5) / (4 + square(_user_text.length)))}px 微软雅黑`, align: "center", fill: "#FFF" });
    user.position.x = cen_point.x - user.width / 2;
    user.position.y = cen_point.y + user.height * 1.5;
    cen.addChild(user);

    /*
     * 进入路途按钮
     */
    var btn = new PIXI.Container();
    btn.interactive = true;
    btn.buttonMode = true;
    current_stage.addChild(btn);
    var btn_point = new PIXI.Point();
    btn_point.x = VIEW_CENTER.x
    if (VIEW_HEIGHT >= VIEW_WIDTH * 1.618) {// 按钮分布的位置，如果是超过黄金比例的竖屏，那么就显示在圈外
        // 圈外
        btn_point.y = VIEW_HEIGHT - (VIEW_HEIGHT - cen_point.y - _loader_width) * 0.618 //+ pt2px(20/*按钮大小为20pt*/);
    } else {
        // 圈内
        btn_point.y = cen_point.y + _loader_width * 0.618;
    }
    // btn.pivot = btn_point;
    btn.position = btn_point;
    // PS: 按钮文字大小是固定的，和圈大小无关
    var button_text = new PIXI.Text("进入丛林", { font: "14pt 微软雅黑", align: "center", fill: "#FFF" });
    button_text.x = -button_text.width / 2;
    btn.addChild(button_text);
    // 点击跳转
    on(btn, "click|tap", function () {
        // alert("跳转");
        jump_next_ani();
    });
    var button_arrow = new PIXI.Container();
    btn.addChild(button_arrow);
    // 箭头·圆圈
    var _base_unit_len_2 = button_text.height / Math.sqrt(2);
    var _base_unit_len = _base_unit_len_2 / 2;
    var button_arrow_1 = SVGGraphics.importFromSVG(`<circle cx="0" cy="0" r="${_base_unit_len * Math.sqrt(2)}" stroke="#FFF"  stroke-width="1" fill="rgba(0,0,0, 0)" />`)._graphics;
    button_arrow.addChild(button_arrow_1);
    button_arrow.y = button_arrow_1.height / 2;
    button_arrow.x = button_text.width / 2 + button_arrow_1.width;
    // 箭头·三角
    var _scale_xy = _base_unit_len * 0.8 / 10;
    var _h = _base_unit_len / 3;
    var _x = (Math.sqrt(175) + 5) / 2 * _scale_xy;
    var _y = (5 - _x) * _scale_xy - _base_unit_len / 6;
    var button_arrow_2 = SVGGraphics.importFromSVG(`<path fill="rgba(0, 0, 0, 0)" stroke-width="1" d="M-${_x},${_y} L0,${_h} L${_x},${_y}" stroke="rgba(255, 255, 255, 0.9)" ></path>`)._graphics;
    button_arrow_2["currentPath"].shape.closed = false;
    // button_arrow_2.width = button_arrow_2.height = button_text.height;
    button_arrow_2.rotation = - Math.PI / 2;
    button_arrow.addChild(button_arrow_2);
    // 箭头·横线
    var _button_arrow_3_len_1_2 = _base_unit_len_2 * Math.SQRT2;
    var _button_arrow_3_len = _button_arrow_3_len_1_2 * 2;
    var button_arrow_3 = SVGGraphics.importFromSVG(`<path fill="rgba(0, 0, 0, 0)" stroke-width="1" stroke="rgba(255, 255, 255, 0.9)" d="M-${_base_unit_len_2},0 L-${_button_arrow_3_len + _base_unit_len_2},0"></path>`)._graphics;
    button_arrow.addChild(button_arrow_3);

    /*
     * 交互与动画
     */
    // 动画控制器
    ani_ticker.add(() => {
        ani_tween.update();
        jump_tween.update();
    });
    // 动画
    cen.alpha = 0;
    cen.scale.x = 0;
    cen.scale.y = 0;
    btn.alpha = 0;
    button_arrow_3.alpha = 0;
    var _in_btn = false;
    var _init_ani_time = L_ANI_TIME;
    // 圆圈初始化动画1

    ani_tween.Tween(cen)
        .delay(M_ANI_TIME)
        .to({ alpha: 1 }, _init_ani_time)
        .easing(TWEEN.Easing.Quadratic.In)
        // .start()
        .onComplete(() => {
            // 显示按钮
            ani_tween.Tween(btn)
                .to({ alpha: 1 }, B_ANI_TIME)
                .easing(TWEEN.Easing.Quintic.In)
                .start();
            // 按钮hover动画
            var _btn_ani_time = S_ANI_TIME;
            var _btn_mouseover = ani_tween.Tween(button_arrow_1)
                .to({// 圆圈隐藏掉
                    alpha: 0
                }, _btn_ani_time)
                .with(
                ani_tween.Tween(button_arrow_2)
                    .to({// 三角右移
                        x: _base_unit_len
                    }, _btn_ani_time)
                // .debug(true)
                ,
                ani_tween.Tween(button_arrow_3)
                    .to({// 箭头右移、缩小、显示
                        x: _base_unit_len_2,
                        width: _button_arrow_3_len_1_2,
                        alpha: 1
                    }, _btn_ani_time)
                )
            var _btn_mouseout = ani_tween.Tween(button_arrow_1)
                .to({// 圆圈显示
                    alpha: 1
                }, _btn_ani_time)
                .with(
                ani_tween.Tween(button_arrow_2)
                    .to({// 三角左移
                        x: 0
                    }, _btn_ani_time),
                ani_tween.Tween(button_arrow_3)
                    .to({// 箭头左移、还原、隐藏
                        x: 0,
                        width: _button_arrow_3_len,
                        alpha: 0
                    }, _btn_ani_time)
                )
            on(btn, "touchstart|mouseover", function () {
                _in_btn = true;
                _btn_mouseout.stop();
                _btn_mouseover.start();
            });
            on(btn, "touchout|touchendoutside|mouseout", function () {
                _in_btn = false;
                _btn_mouseover.stop();
                _btn_mouseout.start();
            });
        });
    // 圆圈初始化动画2
    ani_tween.Tween(cen.scale)
        .delay(M_ANI_TIME)
        .to({ x: 1, y: 1 }, _init_ani_time + B_ANI_TIME)
        .easing(TWEEN.Easing.Back.Out)
        // .start()
        .onComplete(() => {
            // 圆圈over动画
            var _cen_mouseover = ani_tween.Tween(cen.scale)
                .to({ x: 1.1, y: 1.1 }, M_ANI_TIME)
                .easing(TWEEN.Easing.Back.Out);
            var _cen_mouseout = ani_tween.Tween(cen.scale)
                .to({ x: 1, y: 1 }, M_ANI_TIME)
                .easing(TWEEN.Easing.Back.InOut);
            on(grap, "touchstart|mouseover", function () {
                _cen_mouseout.stop();
                _cen_mouseover.start();
            });
            on(grap, "touchend|touchendoutside|mouseout", function () {
                if (_in_btn) {
                    return
                }
                _cen_mouseover.stop();
                _cen_mouseout.start();
            });

        });
    // 场景切换API
    function jump_next_ani() {
        ani_tween.lock(true);

        const ani = (tween: Tween) => {
            return tween
                .easing(TWEEN.Easing.Quintic.Out)
                .start();
        }
        const move_to_left_top = (obj) => {
            return ani(jump_tween.Tween(obj)
                .to({
                    x: 0,
                    y: 0
                }, L_ANI_TIME));
        }
        const fade = (obj) => {
            return ani(jump_tween.Tween(obj)
                .to({
                    alpha: 0
                }, L_ANI_TIME));
        }
        // 圆圈放大渐隐
        const _to_scale_value = Math.sqrt(Math.pow(VIEW_HEIGHT - cen_point.y, 2) + Math.pow(VIEW_WIDTH - cen_point.x, 2)) / _loader_width * 1.2;
        ani(jump_tween.Tween(grap.scale)
            .to({
                x: _to_scale_value,
                y: _to_scale_value
            }, L_ANI_TIME));
        fade(grap);
        // 文字上移
        move_to_left_top(title.position);
        move_to_left_top(time.position);
        move_to_left_top(user.position);
        // 文字隐藏
        fade(time);
        fade(user);
        // 按钮隐藏
        fade(btn);
        // 背景隐藏
        fade(bg_img)
            .onComplete(() => {
                stageManager.next();
            });
    };

    // 帧率
    var FPS_Text = new PIXI.Text("FPS:0", { font: '24px Arial', fill: 0xffffff33, align: "right" });

    current_stage.addChild(FPS_Text);
    FPS_ticker.add(function () {
        FPS_Text.text = "FPS:" + FPS_ticker.FPS.toFixed(2);
    });

    init_w.ok(0, []);

}
current_stage.on("init", initStage);

const init_w = new When(2, () => {
    ani_tween.start();
    jump_tween.start();
    ani_ticker.start();
    FPS_ticker.start();
});
export function initStage() {
    init_w.ok(1, []);
}

